package com.pi.config;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.pi.framework.core.security.JwtAuthenticationConfig;
import com.pi.framework.core.security.JwtAuthenticationEntryPoint;
import com.pi.framework.core.security.JwtAuthenticationTokenFilter;
import com.pi.framework.core.security.JwtUsernamePasswordAuthenticationFilter;

import lombok.extern.slf4j.Slf4j;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	private static final String[] URLS = { "/", "/h2-console", "/*.html", "/static/**", "/**/*.html", "/**/*.css",
			"/**/*.js", "/**/*.jpg", "/**/*.png", "/favicon.ico", "/**/font/**", "/swagger-resources/**",
			"/webjars/**", "/**/api-docs/**" };

	@Value("${security.url.permitAll}")
	private String permitAllUrl;

	@Value("${security.jwt.route.authentication.login:/auth}")
	private String authUrl;

	@Value("${security.jwt.route.authentication.logout}")
	private String logoutUrl;

	@Autowired
	private JwtAuthenticationEntryPoint unauthorizedHandler;

	@Autowired
	private UserDetailsService userDetailsService;

	@Bean
	@Order(830100010)
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Bean
	@Order(830100020)
	public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
		return new JwtAuthenticationTokenFilter();
	}

	/**
	 * @Bean public AuthenticationManager authenticationManager() throws
	 *       Exception { return new OAuth2AuthenticationManager(); }
	 **/

	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception {
		Set<String> defaultUrls = new HashSet<String>();
		defaultUrls.addAll(Arrays.asList(URLS));
		if (permitAllUrl != null && !StringUtils.isBlank(permitAllUrl)) {
			defaultUrls.addAll(Arrays.asList(permitAllUrl.split(",")));
		}
		log.info("Urls granted to annoymouse access: {}", defaultUrls);
		httpSecurity.headers().frameOptions().sameOrigin().and().authorizeRequests()
				// we don't need CSRF because our token is invulnerable
				.and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
				// don't create session
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
				// .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
				// allow anonymous resource requests
				.antMatchers(defaultUrls.toArray(new String[0])).permitAll().antMatchers(authUrl).permitAll()
				.antMatchers(logoutUrl).permitAll().antMatchers("/auth/**").permitAll().anyRequest().authenticated();
		// http://localhost:7080/swagger-resources/configuration/ui
		// Custom JWT based security filter
		httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

		// disable page caching
		httpSecurity.headers().cacheControl();
	}

	@Autowired
	public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
		authenticationManagerBuilder.userDetailsService(this.userDetailsService).passwordEncoder(passwordEncoder());
	}

	@Bean
	@Order(830100030)
	public PasswordEncoder passwordEncoder() {
		// Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();
		// return passwordEncoder;
		return new BCryptPasswordEncoder();
	}

}